<template>
  <div class="sidebar">
    <div class="logo">
      <el-button type="primary" @click="router.push('/index'); navigation.clearPath()">BLB-SMT</el-button>
    </div>
    <el-menu router :default-active="activePath()">
      <el-sub-menu v-for="menu in menuList" :index="menu.id.toString()">
        <template #title>
          <el-icon>
            <component :is="menu.icon" />
          </el-icon>
          <span>{{ menu.menuName }}</span>
        </template>
        <el-menu-item v-for="m in menu.children" :index="m.url" @click="open(m)">{{ m.menuName }}</el-menu-item>
      </el-sub-menu>
    </el-menu>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue"
import { useStaffStore } from "@/stores/staff.js"
import axiosInstance from "@/axios/index.js"
import { useNavigationStore } from "@/stores/navigation"
import { useRoute, useRouter } from 'vue-router'

//菜单集合
const menuList = ref([])

const route = useRoute()
const router = useRouter()
let navigation = useNavigationStore()

//获取菜单数据接口
const getMenu = async () => {
  const res = await axiosInstance.get("role-menu/getStaffMenu", {
    params: { id: useStaffStore().staffInfo.staff.id },
  })
  if (res.data.code === 200) {
    menuList.value = res.data.data
  }
}

//在渲染前调用接口
onMounted(() => {
  getMenu()
  let path = route.path.split('/')
  path = path.filter(item => item.trim())
  if (path.length == 1) {
    navigation.clearPath()
  }
  if (route.path != '/index' && route.path != '/') {
    navigation.savePath(route.path, route.name)
  }
})

//点击左侧菜单时清除仓库,并把左侧菜单放进仓库
let open = function (data) {
  navigation.clearPath()
  navigation.savePath(data.url, data.menuName)
}

let activePath = function () {
  let path = route.path.split('/')
  path = path.filter(item => item.trim())
  if (navigation.data[0] == undefined) {
    return ''
  }
  return navigation.data[0].path.search(path[0]) != -1 ? '/' + path[0] : ''
}

</script>

<style scoped>
.sidebar {
  height: 100%;
  background-color: white;
  display: flex;
  flex-direction: column;
}

.sidebar .logo {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
  width: 85%;
  margin: 0 auto;
  border-bottom: 1px solid #e5e5e5;
  flex-shrink: 0;
}

.el-menu {
  border: 0 !important;
  overflow-y: scroll;
}

/*隐藏滚动条*/
.el-menu::-webkit-scrollbar {
  display: none;
}

.logo>.el-button {
  width: 100%;
  font-weight: bold;
}
</style>
